#!/bin/bash

# 初始化统计变量
total_count=0       # 总包数
success_count=0     # 成功数
fail_count=0        # 失败数

REPO_PATH="/var/www/html/yumrepo/agiros/kylin-v11-2503/2512/x86_64/release/"

# 检查是否安装了rpmrebuild
if ! command -v rpmrebuild &> /dev/null; then
    echo "错误：未找到rpmrebuild工具，请先安装 (yum install rpmrebuild)"
    exit 1
fi

# 清理当前目录和目标目录下的rpm文件
cd $REPO_PATH
rm -f *.rpm
rm -f ~/rpmbuild/RPMS/x86_64/*.rpm

# 复制源目录下的rpm文件到当前目录
cp /var/www/html/yumrepo/agiros/openeuler2403lts/2506/x86_64/release/*.rpm ./
ls -l *.rpm 2>/dev/null | wc -l

# 先处理重复包  
for oe_file in *.oe2403*.rpm; do
    # 检查文件是否存在
    [ -e "$oe_file" ] || continue
    # 生成对应的不含oe2403的文件名
    non_oe_file=$(echo "$oe_file" | sed 's/\.oe2403//')
    # 检查对应的不含oe2403的文件是否存在
    if [ -e "$non_oe_file" ]; then
        echo "发现重复包:"
        echo "  保留: $oe_file"
        echo "  删除: $non_oe_file"
        rm -f "$non_oe_file"
    fi
done

echo "重复包处理完成"

# 统计当前目录下的有效RPM包总数（提前计数，避免循环中重复判断）
for rpm_file in *.rpm; do
    if [ -f "$rpm_file" ] && [[ "$rpm_file" == *.rpm ]]; then
        ((total_count++))
    fi
done

# 提示开始处理
echo "========================================"
echo "开始批量处理RPM包 → 共发现 $total_count 个有效RPM包"
echo "========================================"
echo

# 循环处理当前目录下所有RPM包
for rpm_file in *.rpm; do
    # 检查是否是有效文件（排除目录或非.rpm文件）
    if [ -f "$rpm_file" ] && [[ "$rpm_file" == *.rpm ]]; then
        echo "【当前处理】：$rpm_file"
        
        # 核心操作：修改Release和Packager（避免重复）
        rpmrebuild --change-spec-preamble='sed -e "s/^\(Release:\s*.*\)oe2403/\1ky11/" -e "s/^\(Release:\s*\)\([0-9.]\+\)$/\1\2.ky11/" -e "s/^\(Release:\s*.*\)\(\.ky11\)\{2,\}$/\1.ky11/" -e "/^Packager:/d" -e "/^Name:/aPackager: ISCAS"' -p "$rpm_file" >/dev/null 2>&1
        
        # 统计成功/失败数量
        if [ $? -eq 0 ]; then
            ((success_count++))
            echo "【结果】✅ 处理成功 → 新包路径：~/rpmbuild/RPMS/x86_64/"
        else
            ((fail_count++))
            echo "【结果】❌ 处理失败（可能是包损坏或依赖缺失）"
        fi
        echo "----------------------------------------"
    fi
done

# 输出最终统计报告
echo "========================================"
echo "转换批量处理完成！【统计结果】"
echo "----------------------------------------"
echo "总处理包数：$total_count 个"
echo "成功处理：$success_count 个"
echo "失败处理：$fail_count 个"
echo "----------------------------------------"
echo "新包默认存放路径：~/rpmbuild/RPMS/x86_64/"
echo "提示：失败包可尝试执行 yum builddep 包名 安装依赖后重试"
echo "========================================"

# 复制转换后的rpm包
rm -f *.rpm
cp ~/rpmbuild/RPMS/x86_64/*.rpm $REPO_PATH
echo "新包已复制到 $REPO_PATH"
ls -l *.rpm 2>/dev/null | wc -l

# 重建yum仓库
createrepo $REPO_PATH
echo "yum仓库重建完成"

